import { Inject, Injectable } from "@nestjs/common";
import { HttpService } from "@nestjs/axios";
import { join } from "path";
import * as fs from "node:fs";
import { v4 as uuidv4 } from "uuid";
import { TransportWithinServiceService } from "../micro/transport/transport-within-service.service";
import { configuration } from "../../../../config/config";
import * as process from "node:process";
import { DicomSystemEvent, SysIntervalMsgType } from "../../../../types/types";
import { NatsClientService } from "@app/nats-client";
import { MapRes } from "../types/types";

interface reqType {
  scanId: number | string;
  imageId?: number | string;
  watchFilePath: string;
  totalImgCount: number;
}

@Injectable()
export class PanelService {
  prefixPath;

  @Inject(NatsClientService)
  private natsClient: NatsClientService;

  constructor(
    private readonly httpService: HttpService,
    private readonly withGateway: TransportWithinServiceService,
  ) {
    this.prefixPath = configuration.systemServer.create_dicom_folder_path;
    console.log(`设置创建dicom影像文件夹的前缀路径为：${this.prefixPath}`);
    this.checkPathExists();
  }

  async handleScan(scanParams) {
    try {
      await this.startBtnChange();
      let dicomFilePath = [];
      let reqParams: reqType[] = [];
      const series = scanParams.scanSeries;
      series.forEach((eachSeries, _) => {
        const scanType = eachSeries.scanType;
        const scanId = eachSeries.scanId;
        const imageIds = eachSeries.imageIds;
        imageIds.forEach((imageId: string) => {
          const eachPathObj = {
            scanId: scanId,
            path: this.createFilePath(imageId),
            totalImgCount: -1,
            scanType: scanType,
            imageId: imageId,
          };
          dicomFilePath.push(eachPathObj);
        });
      });
      reqParams = dicomFilePath.map((eachPath) => {
        return {
          scanId: eachPath.scanId,
          imageId: eachPath.imageId,
          watchFilePath: eachPath.path,
          totalImgCount: -1,
          scanType: eachPath.scanType,
        };
      });
      console.log(`notify image server: ${JSON.stringify(reqParams)}`);
      await this.notifyImageServer(reqParams);
      return MapRes.success();
    } catch (e) {
      console.log(e)
      return MapRes.error({
        msg: e
      });
    }
  }

  startBtnChange() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        this.withGateway.sendSysMsg({
          type: "scanBtnStatus",
          data: {
            status: "move",
          },
        });
      }, 1000);

      setTimeout(() => {
        this.withGateway.sendSysMsg({
          type: "scanBtnStatus",
          data: {
            status: "scan",
          },
        });
      }, 2000);

      setTimeout(() => {
        this.withGateway.sendSysMsg({
          type: "scanBtnStatus",
          data: {
            status: "scanClicked",
          },
        });
      }, 3000);

      setTimeout(() => {
        this.withGateway.sendSysMsg({
          type: "scanBtnStatus",
          data: {
            status: "inActive",
          },
        });
        resolve("");
      }, 4000);
    });
  }

  createScoutFilePath(
    pathCount: number = 1,
    imageIds: string[] = [],
    scanId: any,
  ) {
    console.log("create scout file path,", pathCount);
    const arr = new Array(pathCount).fill(0);

    return arr.map((_, index) => {
      const imagePath = imageIds[index];
      const path = this.createOneFilePath(imagePath);
      return {
        scanId,
        path: path,
        imageId: imagePath,
        scanType: "scout",
      };
    });
  }

  createFilePath(scanId: string) {
    return this.createOneFilePath(scanId);
  }

  createOneFilePath(scanId: string) {
    const createPath = join(this.prefixPath, scanId);
    try {
      fs.mkdirSync(createPath);
    } catch (e) {
      console.log(`创建文件路径错误`, e);
    }
    console.log(`创建的路径为:${createPath}`);
    return createPath;
  }

  checkPathExists() {
    const prefixPath = this.prefixPath;
    if (!fs.existsSync(prefixPath)) {
      // 如果目录不存在,则创建目录
      fs.mkdirSync(prefixPath, { recursive: true });
      console.log(`dicom img store path not exist, '${prefixPath}' created.`);
    } else {
      console.log(`dicom img store path already exists.`);
    }
  }

  async notifyImageServer(reqParams: reqType[]) {
    console.log("通知image-server 系统，创建的文件的路径");
    return new Promise((resolve, reject) => {
      this.natsClient
        .send(SysIntervalMsgType.FROM_SYSTEM_TO_IMAGE_EVENT, {
          cmd: DicomSystemEvent.create_new_fold,
          data: reqParams,
        })
        .subscribe({
          next: () => {
            console.log("收到dicom server监听文件路径的响应：监听成功！");
            resolve("");
          },
          error: (err) => {
            console.log(
              "收到dicom server监听文件路径的响应：监听失败，失败消息为：",
              err.message,
            );
            reject("dicom server连接出现错误");
          },
        });
    });
  }

  async notifyDicomServer(reqParams: reqType[]) {
    console.log("通知dicom-server 系统，创建的文件的路径");
    return new Promise((resolve, reject) => {
      this.natsClient
        .send(SysIntervalMsgType.DICOM_MSG_EVENT, {
          cmd: DicomSystemEvent.create_new_fold,
          data: reqParams,
        })
        .subscribe({
          next: (response) => {
            console.log("收到dicom server监听文件路径的响应：监听成功！");
            resolve("");
          },
          error: (err) => {
            console.log(
              "收到dicom server监听文件路径的响应：监听失败，失败消息为：",
              err.message,
            );
            reject(err.message);
          },
        });
    });
  }
}
